<template>
  <div class="comp">
    <!-- 放图表 -->
    <div class="echarts" ref="broken"></div>
  </div>
</template>
  
  <script>
export default {
  data() {
    return {
      echartsInstance: null,
      allData: [], //业务数据
    };
  },
  mounted() {
    this.initEcharts();
    this.getData();
    //监听窗口变化实现图表自适应
    window.addEventListener("resize", this.adapTive);
    //调用适配方法
    this.adapTive();
  },
  methods: {
    //1. echarts实例初始化
    initEcharts() {
      this.echartsInstance = this.$echarts.init(this.$refs.broken, "dark");
      //设置绘图需要的静态配置项
      let initOptions = {
        // 图例
        legend: {
          show: true,
          icon: "circle",
          top: "12%",
          left: "3%",
        },
        // 标题
        title: {
          text: "▍农作物种植面生长趋势",
          top: "2%",
          left: "2%",
        },
        // 提示
        tooltip: {
          show: true,
          trigger: "axis",
        },
        // 坐标系
        grid: {
          show: false,
          top: "20%",
          left: "3%",
          right: "3%",
          bottom: "5%",
          containLabel: true,
        },
        // x轴
        xAxis: {
          type: "category",
        },
        // y轴
        yAxis: {
          type: "value",
          axisLine: {
            show: true,
          },
        },
      };
      // 绘制基础图表
      this.echartsInstance.setOption(initOptions);
    },
    // 获取业务数据
    async getData() {
      let { data } = await this.$http.get("CropGrowthTrend");
      console.log(data);
      this.allData = data;
      //根据业务继续完善图表
      this.setEcharts();
    },
    // 根据业务完善图表
    setEcharts() {
      // 组装类目数据和系列数据
      let cateData = this.allData[0].content.map((item) => item.month);
      let serData = this.allData.map((item) => {
        // 获取每个城市1-12月份农业数据
        let datas = item.content.map((m) => m.area);
        return {
          name: item.city,
          type: "line",
          data: datas,
          stack: true, //设置堆叠效果
          smooth: true, //设置圆滑曲线
          // areaStyle:{}//设置堆叠填充风格
        };
      });
      //  设置图标绘制项
      let setOptions = {
        xAxis: {
          data: cateData,
        },
        // 图表类型
        series:serData,
      };
      // setOption 合并多次的绘图配置项 完善图表
      this.echartsInstance.setOption(setOptions);
    },
    // 窗口适配方法
    adapTive() {
      let width = this.$refs.broken.offsetWidth;

      let scale = (width / 100) * 3.6;

      let adapOptions = {
        // 图例
        legend: {
          itemGap: scale / 2,
          itemWidth: scale / 2,
          itemHeight: scale / 2,
        },
        // 标题
        title: {
          textStyle: {
            fontSize: scale,
          },
        },
      };
      // 适配绘图
      this.echartsInstance.setOption(adapOptions);
      // 图标适配
      this.echartsInstance.resize();
    },
  },
};
</script>
  
  <style>
</style>